/******************************************************************************
 * Copyright (C) 2015  671643387@qq.com
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 *****************************************************************************/

#include "Shared/Util/OptionSet.h"


namespace Shared {
namespace Util {

    OptionSet::OptionSet(void)
        : _options()
    {

    }

    OptionSet::~OptionSet(void)
    {

    }

    void OptionSet::addOption(Option& option)
    {
        ::std::vector<Option>::const_iterator it = _options.begin();
        for (; it != _options.end(); ++it)
        {
            if (it->name() == option.name())
                return;
        }
        _options.push_back(option);
    }

    void OptionSet::process(::std::vector<::std::string>& args)
    {
        ::std::vector<std::string>::const_iterator argIter = args.begin();
        for (; argIter != args.end();)
        {
            bool unknownArg = true;
            ::std::vector<Option>::iterator optionIter = _options.begin();
            for (; (optionIter != _options.end() && argIter != args.end()); ++optionIter)
            {
                if (optionIter->matchName(*argIter) || optionIter->matchShortName(*argIter))
                {
                    argIter = args.erase(argIter);
                    if (optionIter->hasArgment() && argIter != args.end())
                    {
                        optionIter->set_value(*argIter);
                        optionIter->setValid(true);
                        argIter = args.erase(argIter);
                    }
                    else if (!optionIter->hasArgment()) {
                        optionIter->setValid(true);
                    }
                    unknownArg = false;

                    break;
                }
            }

            if (unknownArg) {
                ++argIter;
            }
        }
    }

}}